import * as path from 'path';
import * as fs from 'fs';
import { SourceMapConsumer } from 'source-map';

const SOURCE_MAP_DIR = path.join(__dirname, '../../', 'source-map-file');
/**
 * 解析 source-map
 */
export const parseSourceMap = async (sourceUrl: string, position: string) => {
  const mapPath = path.join(SOURCE_MAP_DIR, sourceUrl + '.map');
  const line  = position.split(':')[0];
  const column = position.split(':')[1];
  // 读取  source-map 文件
  try {
    const rawSourceMap = fs.readFileSync(mapPath, 'utf8');
    const consumer = await new SourceMapConsumer(rawSourceMap);
    const originalPosition = consumer.originalPositionFor({
      line: parseInt(line),
      column: parseInt(column)
    });
    consumer.destroy();
    return originalPosition;
  } catch (e) {
    return {
      source: sourceUrl,
      line,
      column
    };
  }
}
